package com.qilu.careprogram.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckIdNumberUtil {
    public static boolean validateIdCard(String idNumber) {
        // 基本格式校验（18位）
        String idCardPattern = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$";
        Pattern pattern = Pattern.compile(idCardPattern);
        Matcher matcher = pattern.matcher(idNumber);

        if (!matcher.matches()) {
            return false;
        }

        // 校验码计算（GB 11643-1999标准）
        int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; // 加权因子
        char[] checkCodes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}; // 校验码对照

        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += Character.getNumericValue(idNumber.charAt(i)) * weight[i];
        }

        // 校验码比对
        char lastChar = Character.toUpperCase(idNumber.charAt(17));
        if (checkCodes[sum % 11] != lastChar) {
            return false;
        }

        return true; // 验证通过
    }
}
